package com.qvtu.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qvtu.web.domain.Users;
import com.qvtu.web.service.IUsersService;
import com.qvtu.web.service.impl.UsersServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static java.lang.Integer.parseInt;


@Controller
@Slf4j
public class LoginController {

    @Autowired
    private IUsersService usersService;

    @RequestMapping("/login")
    public String login(){

        return "MainInterface/Login";
    }
    @PostMapping("/login")
    public String formLogin(String name, String password, HttpServletRequest request) {
        if(StringUtils.isBlank(name) || StringUtils.isBlank(password)){
            return "redirect:/login?error";
        }
        QueryWrapper<Users> query = new QueryWrapper<>();
        query.eq("name",name);
        Users user = usersService.getOne(query);
        if(!password.equals(user.getPassword())){
            return "redirect:/login?error";
        }
        request.getSession().setAttribute("loginUser",user);
        log.info("登录成功:"+name);
        return "redirect:/books";
    }
    @RequestMapping ("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        log.info("注销成功:");
        return "redirect:/login";
    }
}
